package sealte.util.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringReader;

public class FileUtil {
	
	public static String readFile(String dir) throws Exception{
		StringBuffer sb = new StringBuffer();
		FileReader fr = null;
		try{
			fr = new FileReader(dir);
			char[] buf = new char[4096];
			int len;
			while((len = fr.read(buf)) != -1){
				String s = new String(buf,0,len);
				sb.append(s);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}finally{
			if(null!=fr){
				fr.close();
			}
		}
		return sb.toString();
	}
	
	public static void writeFile(String str,String fn) throws Exception {
		BufferedReader br = null;
		PrintWriter pw = null;
		StringReader sr = null;
		FileWriter fw = null;
		try{
			sr = new StringReader(str);
			br = new BufferedReader(sr);
			fw = new FileWriter(fn);
			pw = new PrintWriter(fw);
			String s;
			while((s = br.readLine()) != null){
				pw.println(s);
			}
			pw.close();
		}catch(Exception ex){
			ex.printStackTrace();
			throw new Exception(ex.getMessage());
		}finally{
			if(null!=pw){
				pw.close();
			}
			if(null!=fw){
				fw.close();
			}
			if(null!=br){
				br.close();
			}
			if(null!=sr){
				sr.close();
			}
		}
	}
	
}
